package com.qf.zhijia.zhijiasearch.listenner;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.zhijia.zhijiasearch.pojo.Product;
import com.qf.zhijia.zhijiasearch.service.SearchService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Author 岳鹏
 * @Date 2020/9/10
 */

@Configuration
public class ProductListener {

    @Autowired
    SearchService searchService;

    ObjectMapper objectMapper = new ObjectMapper();

    @RabbitListener(queues = "product-queue")
    public void getMessage(Message message, Channel channel) {
        try {
            byte[] bytes = message.getBody();
            String routingKey = message.getMessageProperties().getReceivedRoutingKey();
            long deliveryTag = message.getMessageProperties().getDeliveryTag();

            if (routingKey != null && routingKey.equalsIgnoreCase("api.product.add")){
                //将客户端发来的数据转换
                List<Product> productList = objectMapper.readValue(bytes, new TypeReference<List<Product>>(){});
                for (Product product : productList) {
                    searchService.add(product);
                }
                //手动签收
                channel.basicAck(deliveryTag,false);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
